﻿using RockBus.DataContracts;
using RockBus.Logging.Interfaces;
using RockBus.Messages.Interfaces;
using RockBus.Routing.Interfaces;
using System.Linq;
using System.Reflection;

namespace RockBus.MessageProcessors.MessageRepository
{
    public class ErrorProcessor : IMessageProcessor
    {
        public ErrorProcessor(
            ILogger logger,
            IMessageRepositoryHelper messageRepositoryHelper)
        {
            this.Logger = logger;
            this.MessageRepositoryHelper = messageRepositoryHelper;
        }

        public MessageProcessorEnum ProcessingStep { get { return MessageProcessorEnum.ErrorManager; } }

        public void ProcessMessage(IMessageContext messageContext)
        {
            this.Logger.LogDebug(MethodBase.GetCurrentMethod(), "Processing Error Message for: {0}", messageContext);
            messageContext.Abort();

            // Get the Routingheader
            byte[] routingHeaderByteArray = null;
            var rh = messageContext.RoutingHeaders.FirstOrDefault();
            if (rh != null)
            {
                routingHeaderByteArray = rh.GetByteArray();
            }

            // Get the DeliveryAttemptCount
            int deliveryAttemptCount = 0;
            object deliveryAttemptCountObj = null;
            if (messageContext.GetProperty(RoutingHeader.DeliveryAttemptCountKey, out deliveryAttemptCountObj))
            {
                deliveryAttemptCount = (int)deliveryAttemptCountObj;
            }

            // Store the message (which hasn't been stored before because there's no QueueEntryId)
            var mdError = this.MessageRepositoryHelper.StoreMessage(messageContext.RequestMessage, messageContext.ProcessingData.CorrelationId);

            this.MessageRepositoryHelper.CreateErrorMessage(
                mdError.messageId,
                routingHeaderByteArray,
                deliveryAttemptCount,
                messageContext.GetFaultException());
        }

        public ILogger Logger { get; set; }

        public IMessageRepositoryHelper MessageRepositoryHelper { get; set; }
    }
}